package com.example.myxm.activity;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.myxm.App;
import com.example.myxm.R;
import com.example.myxm.auth.LoginManager;
import com.example.myxm.databinding.ActivityMainBinding;

import java.util.Calendar;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    ActivityMainBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
        btnOncLick();
    }

    //绑定控件
    private void initView() {

    }

    //按钮单击事件
    private void btnOncLick() {
        binding.btNewincomeMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(MainActivity.this, NewInComeActivity.class);
//                startActivity(intent); //跳转到新增收入页面
                showNewIncomeDialog();
            }
        });
        binding.btIncomedetailMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, InComeDetailActivity.class);
                startActivity(intent); //跳转到收入明细页面
            }
        });
        binding.btNewpayMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showExpenseBeanDialog();
            }
        });
        binding.btPayydetailMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, PayDetailActivity.class);
                startActivity(intent);
            }
        });
        binding.btDataanalyseMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, DataAnalyseActivity.class);
                startActivity(intent);
            }
        });
        binding.btSyssettingMain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SysSettingActivity.class);
                startActivity(intent);
            }
        });
    }

    private void showNewIncomeDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.in_come_dialog, null);

        EditText etMoney = dialogView.findViewById(R.id.et_money_newin);
        TextView etTime = dialogView.findViewById(R.id.et_time_newin);
        Spinner spType = dialogView.findViewById(R.id.sp_type_newin);
        EditText etPayer = dialogView.findViewById(R.id.et_payer_newin);
        EditText etRemark = dialogView.findViewById(R.id.et_remark_newin);
        TextView btSave = dialogView.findViewById(R.id.bt_save_newin);
        TextView btCancel = dialogView.findViewById(R.id.bt_cancel_newin);
        TextView btTitle = dialogView.findViewById(R.id.tv_payer_newin);
        btTitle.setText("付款方");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView);

        builder.setCancelable(false);


        AlertDialog dialog = builder.create();

        etTime.setOnClickListener(v -> {
            Calendar now = Calendar.getInstance();
            DatePickerDialog datePicker = new DatePickerDialog(this,
                    (view, year, month, dayOfMonth) -> {
                        int selYear = year;
                        int selMonth = month;
                        int selDay = dayOfMonth;

                        TimePickerDialog timePicker = new TimePickerDialog(this,
                                (timeView, hourOfDay, minute) -> {
                                    String result = String.format(
                                            Locale.getDefault(),
                                            "%04d-%02d-%02d %02d:%02d",
                                            selYear,
                                            selMonth + 1,
                                            selDay,
                                            hourOfDay,
                                            minute
                                    );
                                    etTime.setText(result);
                                },
                                now.get(Calendar.HOUR_OF_DAY),
                                now.get(Calendar.MINUTE),
                                true // 是否 24 小时制
                        );

                        timePicker.show();

                    },
                    now.get(Calendar.YEAR),
                    now.get(Calendar.MONTH),
                    now.get(Calendar.DAY_OF_MONTH)
            );
          ;
            datePicker.show();
        });

        btCancel.setOnClickListener(v -> dialog.dismiss());


        btSave.setOnClickListener(v -> {
            String money = etMoney.getText().toString().trim();
            String time = etTime.getText().toString().trim();
            String type = spType.getSelectedItem() != null
                    ? spType.getSelectedItem().toString()
                    : "";
            String payer = etPayer.getText().toString().trim();
            String remark = etRemark.getText().toString().trim();

            if (money.isEmpty() || time.isEmpty()) {
                Toast.makeText(this, "金额和日期不能为空", Toast.LENGTH_SHORT).show();
                return;
            }


            App.getDbHelperStatic().addIncomeBean(LoginManager.getCurrentUserId(this), Double.parseDouble(money), time, type, payer, remark);
            Toast.makeText(this, "新增收入已保存", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });

        // 7. 显示对话框，并让它居中显示
        dialog.show();
        Window window = dialog.getWindow();
        if (window != null) {
            // 设置对话框宽度为屏幕宽度的 80%，高度自适应
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.8f);
            // 保持高度 wrap_content
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.gravity = Gravity.CENTER;  // 居中显示
            window.setAttributes(params);
        }
    }

    private void showExpenseBeanDialog() {
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.in_come_dialog, null);

        EditText etMoney = dialogView.findViewById(R.id.et_money_newin);
        TextView etTime = dialogView.findViewById(R.id.et_time_newin);
        Spinner spType = dialogView.findViewById(R.id.sp_type_newin);
        EditText etPayer = dialogView.findViewById(R.id.et_payer_newin);
        EditText etRemark = dialogView.findViewById(R.id.et_remark_newin);
        TextView btSave = dialogView.findViewById(R.id.bt_save_newin);
        TextView btCancel = dialogView.findViewById(R.id.bt_cancel_newin);
        TextView btTitle = dialogView.findViewById(R.id.tv_payer_newin);
        btTitle.setText("收款方");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(dialogView);

        builder.setCancelable(false);


        AlertDialog dialog = builder.create();

        etTime.setOnClickListener(v -> {
            Calendar now = Calendar.getInstance();
            DatePickerDialog datePicker = new DatePickerDialog(this,
                    (view, year, month, dayOfMonth) -> {
                        int selYear = year;
                        int selMonth = month;
                        int selDay = dayOfMonth;

                        TimePickerDialog timePicker = new TimePickerDialog(this,
                                (timeView, hourOfDay, minute) -> {
                                    String result = String.format(
                                            Locale.getDefault(),
                                            "%04d-%02d-%02d %02d:%02d",
                                            selYear,
                                            selMonth + 1,
                                            selDay,
                                            hourOfDay,
                                            minute
                                    );
                                    etTime.setText(result);
                                },
                                now.get(Calendar.HOUR_OF_DAY),
                                now.get(Calendar.MINUTE),
                                true // 是否 24 小时制
                        );
                        timePicker.show();

                    },
                    now.get(Calendar.YEAR),
                    now.get(Calendar.MONTH),
                    now.get(Calendar.DAY_OF_MONTH)
            );
            datePicker.show();
        });

        btCancel.setOnClickListener(v -> dialog.dismiss());


        btSave.setOnClickListener(v -> {
            String money = etMoney.getText().toString().trim();
            String time = etTime.getText().toString().trim();
            String type = spType.getSelectedItem() != null
                    ? spType.getSelectedItem().toString()
                    : "";
            String payer = etPayer.getText().toString().trim();
            String remark = etRemark.getText().toString().trim();

            if (money.isEmpty() || time.isEmpty()) {
                Toast.makeText(this, "金额和日期不能为空", Toast.LENGTH_SHORT).show();
                return;
            }


            App.getDbHelperStatic().addExpenseBean(LoginManager.getCurrentUserId(this), Double.parseDouble(money), time, type, payer, remark);
            Toast.makeText(this, "新增支出已保存", Toast.LENGTH_SHORT).show();
            dialog.dismiss();
        });

        // 7. 显示对话框，并让它居中显示
        dialog.show();
        Window window = dialog.getWindow();
        if (window != null) {
            // 设置对话框宽度为屏幕宽度的 80%，高度自适应
            WindowManager.LayoutParams params = window.getAttributes();
            params.width = (int) (getResources().getDisplayMetrics().widthPixels * 0.8f);
            // 保持高度 wrap_content
            params.height = WindowManager.LayoutParams.WRAP_CONTENT;
            params.gravity = Gravity.CENTER;  // 居中显示
            window.setAttributes(params);
        }
    }
}
